package checker;

import readers.QueryStringHandler;
import readers.Reader;
import readers.UserReader;
import validator.*;

/**
 * Checks whether an user has login capabilities
 * The lastError should return a meaningful error
 * @author Chris
 */
public class checkerUser extends checker {
    public checkerUser() { err = ERRORS.VALID; }
    
    public boolean isValid (String query) {
        QueryStringHandler qsh = new QueryStringHandler(query);
        String userName = qsh.getElement("username");
        String password = qsh.getElement("password");
        return isValid(userName, password);
    }
    
    public boolean isValid(String userName, String password) {
        validator val;
        
        val = new validUserName();
        //Check for user
        if(!val.isValid(userName) || !Reader.fileExists(Reader.readLocation + userName+"_password.txt")) {
            err = ERRORS.INVALID_USERNAME;
            return false;
        }
        
        //Check the password contains only valid characters
        val = new validPW();
        if(!val.isValid(password)) {
            err = ERRORS.INVALID_PW;
            return false;
        }
        
        //Read in the actual user's password and return the result
        String pw = UserReader.getPassword(userName);
        if(pw.equals("") ||
           !pw.equals(password)) {
            err = Errors.ErrorInformation.ERRORS.INVALID_PW;
            return false;
        }
        
        err = Errors.ErrorInformation.ERRORS.VALID;
        return true;
    }
}
